import Vue from 'vue';
import Router from 'vue-router';
import { Message } from 'element-ui'
const load = (path) => { // 路由懒加载
    return () => Promise.resolve(require(`@/views/${path}`).default)
}

/* 登录页 */
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
const Home = load('home/Home.vue');
/**error 401 */
const Page401 = load('errorPage/401.vue');
/**看板 */
const Dashboard = load('dashboard/index.vue');
/**欢迎页 */
const Welcome = load('Welcome.vue');


/**药品分类 */
const DrugManage = load('drug/DrugManage.vue');
/**药店管理 */
const DrugShopManage = load('drug/DrugShopManage.vue');
/**店员登记 */
const Recorder = load('recorder/index.vue');
/**购药登记 */
const PayInfo = load('payInfo/index.vue');

import NProgress from 'nprogress';

Vue.use(Router);
let constRouters = [
    {
        path: '/',
        hidden: true,
        redirect: {
            name: 'login'
        }
    },
    {
        path: '/login',
        name: 'login',
        component: Login,
        hidden: true,
        meta: {
            title: '登录'
        }
    },
    {
        path: '/register',
        name: 'register',
        component: Register,
        hidden: true,
        meta: {
            title: '注册'
        }
    },
    {
        path: '/',
        component: Home,
        icon: 'quickStart',
        hidden: true,
        leaf: true, //只有一个节点
        meta: {
            title: '错误页面'
        },
        children: [
            {
                path: '/401',
                component: Page401,
                name: '401',
                meta: {
                    title: '无权限'
                }
            }
        ]
    },

];
let permissonRoutes = [
    {
        path: '/',
        component: Home,
        leaf: true, //只有一个节点
        hidden: false,
        icon: 'el-icon-s-data',
        name: '看板',
        meta: {
            auth: ['1', '2']
        },
        children: [
            {
                path: '/dashboard',
                name: '看板',
                component: Dashboard,
                meta: {
                    title: '看板',
                    auth: ['1']
                }
            },
            {
                path: '/dashboard',
                name: '看板',
                component: Welcome,
                meta: {
                    title: '看板',
                    auth: ['2']
                }
            }
        ]
    },
    {
        path: '/',
        component: Home,
        leaf: false, //只有一个节点
        name: '药品分类',
        icon: 'el-icon-folder-add',
        meta: {
            title: '药品分类',
            auth: ['1']
        },
        children: [
            {
                path: '/drugManage',
                name: '药品管理',
                component: DrugManage,
                meta: {
                    title: '药品管理',
                    auth: ['1']
                }
            }
        ]
    },
    {
        path: '/',
        component: Home,
        leaf: false, //只有一个节点
        name: '药店管理',
        icon: 'el-icon-s-shop',
        meta: {
            title: '药店管理',
            auth: ['1']
        },
        children: [
            {
                path: '/shopManage',
                name: '药店管理',
                component: DrugShopManage,
                meta: {
                    title: '药店管理',
                    auth: ['1']
                }
            }
        ]
    },
    {
        path: '/',
        component: Home,
        leaf: false, //只有一个节点
        name: '店员管理',
        icon: 'el-icon-user-solid',
        meta: {
            title: '店员管理',
            auth: ['2']
        },
        children: [
            {
                path: '/recorder',
                name: '店员录入',
                component: Recorder,
                meta: {
                    title: '店员录入',
                    auth: ['2']
                }
            }
        ]
    },
    {
        path: '/',
        component: Home,
        leaf: false, //只有一个节点
        name: '购药管理',
        icon: 'el-icon-s-goods',
        meta: {
            title: '购药管理',
            auth: ['1', '2']
        },
        children: [
            {
                path: '/payInfo',
                name: '购买人登记',
                component: PayInfo,
                meta: {
                    title: '购买人登记',
                    auth: ['1', '2']
                }
            }
        ]
    },

    { path: '*', redirect: { name: '401' }, hidden: true }
];

const router = new Router({
    base: '/',
    routes: constRouters,
    // mode: process.env.IS_ELECTRON?'hash':'history'
});

/**
 * 递归查询
 */
function filterAsyncRoutes(routes, roles) {
    const res = [];
    routes.forEach(route => {
        const tmp = { ...route };
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles);
            }
            res.push(tmp);
        }
    });
    return res;
}
/**
 * 过滤路由
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.auth) {
        return roles.some(role => route.meta.auth.includes(role));
    } else {
        return true;
    }
}

function hasRoute(routes, path) {
    if (JSON.stringify(routes).includes(path)) {
        return true;
    } else {
        return false;
    }
}
// 免登录路径
const whitelist = ['/login', '/register'];
// 避免无权限时重复生成路由
var filterRoutes = [];

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    const hasToken = sessionStorage.getItem('jwtToken');
    if (hasToken) {
        if (to.path === '/login') {
            next()
            NProgress.done()
        } else {
            if (filterRoutes.length == 0) {
                try {
                    var authlist = sessionStorage.getItem("admin") ? sessionStorage.getItem("admin").split(",") : [];
                    filterRoutes = filterAsyncRoutes(permissonRoutes, authlist);
                    router["options"].routes = [...constRouters, ...filterRoutes];
                    router.addRoutes(filterRoutes);
                    next({ ...to });
                } catch (err) {
                    Message.error(err || 'Verification failed, please login again')
                    next(`/login?redirect=${to.path}`)
                    sessionStorage.clear();
                    NProgress.done()
                }
            } else {
                next()
            }
        }
    } else {
        if (whitelist.indexOf(to.path) !== -1) {
            next()
        } else {
            next({ path: `/login`, replace: true })
            // next({ path: `/login?redirect=${to.path}`, replace: true })
            NProgress.done()
        }
    }
})

router.afterEach((to, from) => {
    NProgress.done();
});

// 解决Loading chunk (\d)+ failed问题
router.onError((error) => {
    console.error(error)
    const pattern = /Loading chunk/g
    const isChunkLoadFailed = error.message.match(pattern)
    console.log('router_error', router)
    const targetPath = (router as any).history.pending.fullPath
    if (isChunkLoadFailed && error['type'] == 'missing') {
        router.push(targetPath)
    }
})
export default router;
